#!/usr/bin/perl
##########################################################################################################################
##### a script to add emoticons to Wigan-Warriors.com
##########################################################################################################################

##########################################################################################################################
######  TODO list  #######################################################################################################
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
###### Bug list
##########################################################################################################################
##########################################################################################################################

##########################################################################################################################
# Includes
##########################################################################################################################

use lib qw(../cgi-bin);
use Sys::Hostname;
use Time::Local qw(timelocal);
use CGI;

use Diva::DB;
use Diva::DataObject;
use WiganRL::DataObject qw(:constants);
use WiganRL::DataObject::View;
use WiganRL::Search;
use WiganRL::DataObject::Matchstats;
use WiganRL::DataObject::Player;
use WiganRL::DataObject::Image;

use Getopt::Long;
use File::Glob;
use File::Basename;

use strict;
#use warnings;

$|++;  #unbuffered

##########################################################################################################################
# get arguments
##########################################################################################################################

WiganRL::DataObject->init_class();
WiganRL::Search->init_class();

##########################################################################################################################
# site setup and location variable declarations
##########################################################################################################################
my $host= hostname;
my ($SITE_BASE_URL,$SITE_BASE_DIR,$CGI_BASE_URL,$CGI_BASE_DIR,$EMAIL_BASE_DIR,$MAIL_SMTP_SERVER);
my ($SEND_EMAILS,$ADMIN_NAME,$ADMIN_EMAIL,$MAIL_SCRIPT,$SITE_DATA_DIR);

	$SITE_BASE_URL= 'http://localhost/wigan';
	$SITE_BASE_DIR= '/wwcom/html';
	$SITE_DATA_DIR= '/wwcom/data';
	$CGI_BASE_URL= 'http://localhost/cgi-bin/wigan';
	$CGI_BASE_DIR= '/wwcom/cgi-bin';

my $cgi= CGI->new();
$cgi->param('CGI_BASE_URL',$CGI_BASE_URL);
$cgi->param('SessionID','');

my $dbh= Diva::DB->new();
$dbh->set( {
	DATABASE_NAME       => 'wwcom',
	DATABASE_SERVER     => 'localhost:3306',
	DATABASE_USERNAME   => 'wwcom',
	DATABASE_PASSWORD   => 'wwcom',
	DATABASE_TYPE       => 'mysql',
	} );
$dbh->connect();
$dbh->debug(0);

WiganRL::DataObject->dbh($dbh);
WiganRL::DataObject->cgi($cgi);
WiganRL::DataObject->datadir($SITE_DATA_DIR);
WiganRL::DataObject->dataurl('data');

WiganRL::Search->dbh($dbh);
#WiganRL::DataObject::User->dbh($dbh);
Diva::DataObject->init_contenttypes();  #loads contenttypes

$Diva::DB::_SQL_DEBUG= 0;


#define start URL
my $rootURL= 'http://www.wiganwarriors.com/gallery.asp';
#download and get HTML
my ($url,$rootfname)= WiganRL::DataObject->download_file($rootURL,'tmp');
open(FID,"<$rootfname"); 
my $rootHTML=  join('',<FID>);
close(FID);


#get match pages
my %matchIDs;
while ($rootHTML=~ /gallery\.asp\?eid=(\d+)\">([^<]+)/sg) {
	$matchIDs{$1}= $2;
}
for (keys %matchIDs) {
	print "Match - $_: $matchIDs{$_}\n";
}


#get player pages
my %playerIDs;
while ($rootHTML=~ /gallery\.asp\?sid=(\d+)\">([^<]+)/sg) {
	$playerIDs{$1}= $2;
}
for (keys %playerIDs) {
	print "Player - $_: $playerIDs{$_}\n";
}

#now scan all match pages
my $squadID= 123033;
my %images;
for my $mID (keys %matchIDs) {
	#get match date
	my $matchDate;
	if ($matchIDs{$mID}=~ /^(\d+)\/(\d+)\/(\d+)/ ) {
		$matchDate= sprintf("%04d-%02d-%02d",$3+2000,$2,$1);
	} else {
		next;
	}

	print "Scanning match: $mID, $matchDate, $matchIDs{$mID}\n";

	#find matching match in the database
	my $s= WiganRL::Search->new;
	$s->table('MATCHSTATS');
	$s->where("DATE_FORMAT(MATCH_KOTIME,'%Y-%m-%d')='$matchDate' 
		and (FK_HOMESQUAD_ID='$squadID' or FK_AWAYSQUAD_ID='$squadID')");
	my $res= $s->search;
	if ($#$res<0) {
		print "Could not find matching game\n";
		next;
	}
	print "Found match: ".$res->[0]->id.": ".$res->[0]->get_field('MATCHSTATS_RESULT')."\n";
	my $wwcomID= $res->[0]->id;	


	#download page
	my ($url,$fname)= WiganRL::DataObject->download_file('http://www.wiganwarriors.com/gallery.asp?eid='.$mID,'tmp');
	open(FID,"<$fname"); 
	my $pageHTML=  join('',<FID>);
	close(FID);
	
	#scan for linked images
	while ($pageHTML=~ /pop\.asp\?fn=([^\']+)/sg) {
		print "\tFound Image: $1\n";
		$images{$1}{date}= $matchDate;
		$images{$1}{match}= $mID;
		$images{$1}{wwcommatch}= $wwcomID;
		$images{$1}{matchloc}= "at the JJB";
		if ($res->[0]->data('FK_AWAYSQUAD_ID')==$squadID) {
			$images{$1}{matchloc}= "at ".$res->[0]->get_field('MATCHSTATS_HOMECLUB_CLUB_NAME');
		}
	}
}


#now scan all player pages
for my $pID (keys %playerIDs) {
	#get match date
	print "Scanning player: $pID, $playerIDs{$pID}\n";

	#find matching match in the database
	my $pName= $playerIDs{$pID};
	my $s= WiganRL::Search->new;
	$s->table('PLAYER');
	$s->where("PLAYER_NAME=".$dbh->{_DBH}->quote($pName));
	my $res= $s->search;
	if ($#$res<0) {
		print "Could not find matching player\n";
		next;
	}
	print "Found player: ".$res->[0]->id.": ".$res->[0]->data('PLAYER_NAME')."\n";
	my $wwcomID= $res->[0]->id;	


	#download page
	my ($url,$fname)= WiganRL::DataObject->download_file('http://www.wiganwarriors.com/gallery.asp?sid='.$pID,'tmp');
	open(FID,"<$fname"); 
	my $pageHTML=  join('',<FID>);
	close(FID);
	
	#scan for linked images
	while ($pageHTML=~ /pop\.asp\?fn=([^\']+)/sg) {
		print "\tFound Image: $1\n";
		if (defined $images{$1}{wwcomplayer}) {
			$images{$1}{wwcomplayer}.= ",$wwcomID";
			$images{$1}{playername}.= " and ".$res->[0]->data('PLAYER_NAME');
			$images{$1}{playerlink}.= ",".$res->[0]->data('PLAYER_NAME');
		} else {
			$images{$1}{player}= $pID;
			$images{$1}{wwcomplayer}= $wwcomID;
			$images{$1}{playername}= $res->[0]->data('PLAYER_NAME');
			$images{$1}{playerlink}= $res->[0]->data('PLAYER_NAME');
		}
	}
}

#scan images for cross referenced images
$cgi->param('UserID',12032);
for my $im (keys %images) {
	print "Image: $im\n";
	print "\tPlayer: $images{$im}{player}\n";
	print "\tWWCOM Player: $images{$im}{wwcomplayer}\n";
	print "\tMatch: $images{$im}{match}\n";
	print "\tWWCOM Match: $images{$im}{wwcommatch}\n";
	print "\tDate: $images{$im}{date}\n";
	#look for image in database
	my $imURL= 'http://www.wiganwarriors.com/imagelibrary/'.$im;
	my $imFile= $im;
	$imFile=~ s/%20//eg;
	$imFile=~ s/\?//eg;
	$imFile= "$SITE_DATA_DIR/incoming/images/players/$imFile";
	if (-e $imFile) {
		print "\tImage already exists: $imFile\n\n";
		next;
	}
	#update into database!
	if ($images{$im}{wwcomplayer} and $images{$im}{wwcommatch}) {
		$cgi->param('IMAGE_URL',$imURL);
		$cgi->param('IMAGE_CAPTION',
			$images{$im}{playername}." in action ".$images{$im}{matchloc});
		$cgi->param('IMAGE_DESCRIPTION',
			$images{$im}{playername}." in action ".$images{$im}{matchloc}.".");
		$cgi->param('OBJECT_LINKS',
			$images{$im}{playerlink});
		$cgi->param('IMAGE_DATE',
			$images{$im}{date});
		$cgi->param('IMAGE_ORIGURL',
			'http://www.wiganwarriors.com/gallery.asp?eid='.$images{$im}{match});
		$cgi->param('FK_NEWSSOURCE_ID',24690);
		$cgi->param('RELATED_MATCHSTATS',
			$images{$im}{wwcommatch});

		my $o= WiganRL::DataObject::Image->new;
		$o->update;
		$o->update_related;
		WiganRL::DataObject::Player->auto_links($o);
		$o->auto_related("WiganRL::DataObject::Player");

	} elsif ($images{$im}{wwcomplayer}) {
		$cgi->param('IMAGE_URL',$imURL);
		$cgi->param('IMAGE_CAPTION',
			$images{$im}{playername});
		$cgi->param('IMAGE_DESCRIPTION',
			$images{$im}{playername}." in 2006.");
		$cgi->param('OBJECT_LINKS',
			$images{$im}{playerlink});
		$cgi->param('IMAGE_DATE','2006-00-00');
		$cgi->param('IMAGE_ORIGURL',
			'http://www.wiganwarriors.com/gallery.asp?sid='.$images{$im}{player});
		$cgi->param('FK_NEWSSOURCE_ID',24690);
		$cgi->param('RELATED_MATCHSTATS','');

		my $o= WiganRL::DataObject::Image->new;
		$o->update;
		$o->update_related;
		WiganRL::DataObject::Player->auto_links($o);
		$o->auto_related("WiganRL::DataObject::Player");
	} 
	exit(0);
}


exit(0);

##get view threads
#my ($sth,$rv)= $dbh->get(['IMAGE'],['FK_OBJECT_ID','IMAGE_THUMBNAIL'],'',
#	"",
#	"","",'','');
#
#while (my $reshash= $sth->fetchrow_hashref) {
#	if (-e '/wwcom/'.$reshash->{'IMAGE_THUMBNAIL'}) {
#		next;
#	}
#	my $o= WiganRL::DataObject::Image->new($reshash->{'FK_OBJECT_ID'});
#	for ('IMAGE_CAPTION'.'IMAGE_DESCRIPTION','IMAGE_URL') {
#		$cgi->param($_,$o->data($_));
#	}
#	$cgi->param('IMAGE_THUMBNAIL',$o->makethumbnail);
#	$o->update;
#	print "Updated Image: $reshash->{FK_OBJECT_ID}, ".$o->data('IMAGE_CAPTION')."\n";
#}
#
#$sth->finish;
#exit(0);
